package alone.sub.table.test.demo.service;

import alone.sub.table.test.demo.exception.DatabaseException;
import alone.sub.table.test.demo.mapper.UserInfoMapper;
import alone.sub.table.test.demo.pojo.UserId;
import alone.sub.table.test.demo.pojo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class UserInfoService {


    @Resource
    private UserInfoMapper userInfoMapper;


    /**
     * 分表插入数据
     * @param name name
     * @param password password
     * @return result
     */
    public String insertData(String name,String password){

        //首先向base表中插入数据获取ID
        UserId userId = new UserId();
        userInfoMapper.insertUserId(userId);
        Integer id = userId.getId();
        log.info("the primary key is ===>>> {}",id);

        //判断并执行插入数据
        UserInfo userInfo = new UserInfo(id,name,password);
        int num = id % 3;
        log.info("the num=id%3 is ===>>>> {}", num);
        switch (num){
            case 0:
                log.info("case 0 | so insert into sub_table_test_zero and the userInfo is {}",userInfo.toString());
                userInfoMapper.insertUserZero(userInfo);
                break;
            case 1:
                log.info("case 1 | so insert into sub_table_test_first and the userInfo is {}",userInfo.toString());
                userInfoMapper.insertUserFirst(userInfo);
                break;
            case 2:
                log.info("case 2 | so insert into sub_table_test_second and the userInfo is {}",userInfo.toString());
                userInfoMapper.insertUserSecond(userInfo);
                break;
        }

        return "success";
    }

    /**
     * 根据id分表查询
     * @param id id
     * @return userInfo
     */
    public UserInfo findUserById(Integer id){

        log.info("the userId is ===>>> {}",id);
        //判断并执行查询
        int num = id % 3;
        log.info("the num=id%3 is ===>>> {}",num);
        UserInfo userInfo = null;
        switch (num){
            case 0:
                userInfo = userInfoMapper.findZeroUserById(id);
                log.info("case 0 | and the userInfo is {}",userInfo.toString());
                break;
            case 1:
                userInfo = userInfoMapper.findFirstUserById(id);
                log.info("case 1 | and the userInfo is {}",userInfo.toString());
                break;
            case 2:
                userInfo = userInfoMapper.findSecondUserById(id);
                log.info("case 2 | and the userInfo is {}",userInfo.toString());
                break;
        }
        return userInfo;
    }

}
